/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function (root) {
  if (!root) return 0;
  if (!root.left && !root.right) return 1;
  let result = 1;
  let depth = 1;

  function getDepth(l, r, _depth) {
    if ((l || r) && depth === _depth) {
      result += 1;
      depth += 1;
    }
    if (l) getDepth(l.left, l.right, _depth + 1);
    if (r) getDepth(r.left, r.right, _depth + 1);
  }

  getDepth(root.left, root.right, 1);

  return result;
};
